import { director, Director, js } from 'cc';

interface ITimer {
    tick: number;
    id: number;
    interval: number;
    repeat: number;
    func: Function;
    target: Object;
}

// 自定义计时器管理
export class TimerMgr {
    private timers: Record<number, ITimer> = {};

    public add(
        delay: number,
        repeat: number,
        func: Function,
        target: Object,
    ) {
        if (repeat == 0) {
            return;
        }

        let id = js.IDGenerator.global.getNewId();
        this.timers[id] = {
            tick: 0,
            id,
            interval: delay,
            repeat: repeat,
            func: func,
            target: target,
        };
        return id;
    }

    public removeById(id: number) {
        if (id in this.timers) {
            delete this.timers[id];
            return true;
        }
        return false;
    }

    public init() {
        director.on(Director.EVENT_BEFORE_UPDATE, this.update, this);
    }

    public update(dt: number) {
        for (const id in this.timers) {
            const element = this.timers[id];
            element.tick += dt;
            if (element.tick >= element.interval) {
                element.tick -= element.interval;
                element.func.call(element.target);
                if (element.repeat > 0) {
                    element.repeat--;
                    if (element.repeat == 0) {
                        this.removeById(parseInt(id));
                    }
                }
            }
        }
    }

    // public remove(func: Function, target: Object) {
    //     for (let index = 0; index < this.timers.length; index++) {
    //         const element = this.timers[index];
    //         if (element.func == func && element.target == target) {
    //             this.timers.splice(index, 1);
    //             index--;
    //             continue;
    //         }
    //     }
    // }
}
